package com.hbsi.demo2;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;

/**
 * @author 程奕红
 * @version 1.0
 */
public class ReflectDemo3 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        //Person   属性
        Class c1=Class.forName("com.hbsi.demo2.Person");
        //1)   getFields()- - -返回所有的public 属性
        Field[]  farr=c1.getFields();
        for(Field f:farr){
            System.out.println(f);
        }
        System.out.println("----------------------------------------");//返回所有的属性，无论是什么样的权限
        //2)getDeclaredFields()  - - -返回所有的属性，无论是什么样的权限
        Field[] farr2=c1.getDeclaredFields();
        for(Field f:farr2){
            System.out.println(f);
        }
        System.out.println("================================================");
        //3)getField(name)  getDeclaredField(name)
        //Filed field1=c1.getField("age");
        Field field1=c1.getField("address");
        System.out.println(field1);
        //4)getDeclaredField()- - -不管该属性是什么权限，都能拿到
        Field field2=c1.getDeclaredField("age");//filed2仅仅代表一个属性，还没有对象结果，需要实例对象
        System.out.println(field2);
        Field field3=c1.getDeclaredField("name");
        System.out.println(field3);
       Constructor cons= c1.getConstructor();
      Object object=cons.newInstance();
      field2.set(object,18);//给对象的什么属性设置值
        System.out.println(object);
        field1.setAccessible(true);//暴力访问，因为权限问题
        field1.set(object,"合肥");
        System.out.println(field1.get(object));
        field3.setAccessible(true);
        field3.set(object,"熊大");//field1.set(obj,熊大）  给obj的对象field赋值
        System.out.println(field3.get(object));
    }
}
